import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Tag, Space } from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  CheckOutlined
} from '@ant-design/icons';
import {
  getContractChanges,
  createContractChange,
  updateContractChange,
  deleteContractChange,
  approveContractChange
} from '@/services/contractChange';
import ContractChangeForm from './components/ContractChangeForm';
import ContractForm from '../CustomerContract/components/ContractForms';

const ContractChange = () => {
  const [activeTab, setActiveTab] = useState('待变更');
  const [formVisible, setFormVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [changeFormVisible, setChangeFormVisible] = useState(false);
  const [changingRecord, setChangingRecord] = useState(null);
  const actionRef = useRef();

  // 表格列配置
  const columns = [
    {
      title: '客户编号',
      dataIndex: 'customerCode',
      width: 120,
      fixed: 'left',
      search: {
        transform: (value) => ({ customerCode: value }),
      },
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
      fixed: 'left',
      search: {
        transform: (value) => ({ customerName: value }),
      },
    },
    {
      title: '公司类型',
      dataIndex: 'companyType',
      width: 120,
      valueType: 'select',
      valueEnum: {
        '有限责任公司': { text: '有限责任公司' },
        '股份有限公司': { text: '股份有限公司' },
        '个体工商户': { text: '个体工商户' },
        '合伙企业': { text: '合伙企业' },
        '其他': { text: '其他' },
      },
    },
    {
      title: '原合同月收费',
      dataIndex: 'contractMonthlyFee',
      width: 120,
      hideInSearch: true,
      render: (fee) => `¥${fee?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '变更后合同月收费',
      dataIndex: 'newContractMonthlyFee',
      width: 140,
      hideInSearch: true,
      render: (fee) => fee ? `¥${fee?.toLocaleString()}` : '-',
      sorter: true,
    },
    {
      title: '区域',
      dataIndex: 'area',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '北京': { text: '北京' },
        '上海': { text: '上海' },
        '广州': { text: '广州' },
        '深圳': { text: '深圳' },
        '杭州': { text: '杭州' },
        '其他': { text: '其他' },
      },
    },
    {
      title: '原月收费',
      dataIndex: 'monthlyFee',
      width: 100,
      hideInSearch: true,
      render: (fee) => `¥${fee?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '变更后月收费',
      dataIndex: 'newMonthlyFee',
      width: 120,
      hideInSearch: true,
      render: (fee) => fee ? `¥${fee?.toLocaleString()}` : '-',
      sorter: true,
    },
    {
      title: '合同状态',
      dataIndex: 'contractStatus',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '正常': { text: '正常', status: 'Success' },
        '变更中': { text: '变更中', status: 'Processing' },
        '已变更': { text: '已变更', status: 'Default' },
        '终止': { text: '终止', status: 'Error' },
      },
      render: (status) => {
        let color = 'default';
        switch (status) {
          case '正常':
            color = 'success';
            break;
          case '变更中':
            color = 'processing';
            break;
          case '已变更':
            color = 'default';
            break;
          case '终止':
            color = 'error';
            break;
        }
        return <Tag color={color}>{status}</Tag>;
      },
    },
    // 根据Tab页显示不同的操作列
    ...(activeTab === '待变更' ? [ {
      title: '操作',
      valueType: 'option',
      width: 160,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="change"
          type="link"
          size="small"
          icon={<CheckOutlined />}
          onClick={() => handleApproveChange(record)}
        >
          变更
        </Button>,
        <Button
          key="add"
          type="link"
          size="small"
          icon={<PlusOutlined />}
          onClick={() => handleAdd(record)}
        >
          补收费
        </Button>,
      ]
    }] : [
     
    ]),
  ];

  // 处理新增
  const handleAdd = () => {
    setEditingRecord(null);
    setFormVisible(true);
  };

  // 处理编辑
  const handleEdit = (record) => {
    setEditingRecord(record);
    setFormVisible(true);
  };

  // 处理删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除客户"${record.customerName}"的变更记录吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteContractChange(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理变更审批 - 修改为弹出表单
  const handleApproveChange = (record) => {
    setChangingRecord(record);
    setChangeFormVisible(true);
  };

  // 处理变更表单提交
  const handleChangeFormSubmit = async (values) => {
    try {
      await approveContractChange(changingRecord.id, values);
      message.success('变更成功');
      setChangeFormVisible(false);
      setChangingRecord(null);
      actionRef.current?.reload();
    } catch (error) {
      message.error('变更失败');
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values) => {
    try {
      if (editingRecord) {
        await updateContractChange(editingRecord.id, values);
        message.success('更新成功');
      } else {
        await createContractChange(values);
        message.success('创建成功');
      }

      setFormVisible(false);
      setEditingRecord(null);
      actionRef.current?.reload();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };



  // Tab配置
  const tabList = [
    {
      key: '待变更',
      tab: '待变更',
    },
    {
      key: '变更',
      tab: '变更',
    },
  ];

  return (
    <PageContainer
      header={{
        title: '合同变更',
        subTitle: '合同变更管理页面',
      }}
      tabList={tabList}
      tabActiveKey={activeTab}
      onTabChange={setActiveTab}
    >
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          try {
            const response = await getContractChanges({
              ...params,
              status: activeTab,
            });

            return {
              data: response.data?.list || [],
              success: response.success,
              total: response.data?.total || 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          filterType: 'light',
        }}
        scroll={{ x: 1500 }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        dateFormatter="string"
      />

      <ContractChangeForm
        visible={formVisible}
        title={editingRecord ? '编辑变更' : '新增变更'}
        initialValues={editingRecord}
        onCancel={() => {
          setFormVisible(false);
          setEditingRecord(null);
        }}
        onFinish={handleFormSubmit}
      />

      <ContractForm
        visible={changeFormVisible}
        title={`合同变更 - ${changingRecord?.customerName}`}
        initialValues={changingRecord}
        onCancel={() => {
          setChangeFormVisible(false);
          setChangingRecord(null);
        }}
        onFinish={handleChangeFormSubmit}
      />
    </PageContainer>
  );
};

export default ContractChange; 